<?php

/*
 *	Part of framework
 */
namespace Nano
{
	/*
	 *	Debugger class
	 *
	 *	@extends	\Kernel
	 *	@final
	 */
	final class Debug extends \Kernel
	{
		/*
		 *	$data	array	All collected (debugged) data
		 *
		 *	@protected
		 */
		protected $data = array();
		
		/*
		 *	$startime	int	Start time of debuging
		 */
		public $startime = 0;
		
		/*
		 *	$accuracy	int	Accuracy of microtiming
		 */
		public $accuracy = 7;
		
		/*
		 *	$flash	string	Flash sign when write (empty sign)
		 */
		public $flash = '*flash*';
		
		/*
		 *	Constructor
		 */
		public function __construct()
		{
			$this->startime = $this->microtime();
		
			$this->write('Debugger initialized');
		}
		
		/*
		 *	Convert debug data to a string
		 *
		 *	@todo	Link with template parser or with view
		 *	@return	string
		 */
		public function __toString()
		{
			$result = array();
			
			foreach($this->data as $time => $line)
			{
				$result[] = '['.$time.']: '.$line.';';
			}
			
			return "<pre>\n".implode("\n", $result)."\n</pre>";
		}
		
		/*
		 *	Write line to debug
		 *
		 *	@param	string	Data to write [optional]
		 */
		public function write($line = null)
		{
			$this->data[$this->calc($this->microtime())] = isset($line) ? $line : $this->flash;	
		}
		
		/*
		 *	Calculate difference between start time and seted time
		 *
		 *	@param	string	Microtime
		 *	@return	string	Calculated different
		 */
		public function calc($microtime)
		{
			return bcsub($microtime, $this->startime, (int)$this->accuracy);
		}
		
		/*
		 *	Get total script time
		 *
		 *	@return	string
		 */
		function total()
		{
			return $this->calc($this->microtime());
		}
		
		/*
		 *	Get the exact time (in microseconds)
		 *
		 *	@return	string
		 */
		public function microtime()
		{
			list($usec, $sec) = explode(' ', microtime()); 
			
			return bcadd($usec, $sec, (int)$this->accuracy);
		}
	}
}